package com.yvan.leto.server.controller;

import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.yvan.YvanUtil;
import com.yvan.leto.server.domain.UserAgent;
import com.yvan.leto.server.service.UserService;
import com.yvan.leto.server.utils.HttpJsonPayloadParser;
import com.yvan.leto.server.utils.HttpUtil;
import com.yvan.platform.JsonWapper;
import com.yvan.platform.ResultModel;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@RestController
@Slf4j
public class UsersController {

    @Autowired
    private UserService userService;

    @GetMapping("/users.htm")
    public ModelAndView index() {
        return new ModelAndView("/users.ftl");
    }

    @PostMapping("/users.json")
    public Object getRelease(@RequestParam(value = "rows", required = false, defaultValue = "10") int rows,
                             @RequestParam(value = "page", required = false, defaultValue = "1") int page) {

        Pagination pagination = new Pagination(page, rows);
        List<UserAgent> row = userService.selectByQuery(pagination);
        return HttpUtil.writeJqgridResult(row, pagination);
    }

    @PostMapping("/users/modify.json")
    public Object editPost(HttpServletRequest request) throws IOException {
        HttpJsonPayloadParser parser = new HttpJsonPayloadParser(request);
        JsonWapper jw = parser.getJsonWapper();
        val user = jw.asObject(UserAgent.class);
        user.setLoginPassword(jw.asStr("login_password"));
        val data = userService.createUser(user);
        return ResultModel.newSuccess(data);
    }

    @PostMapping("/user/check_name.json")
    public Object checkName(@RequestParam("login_name") String loginName) {
        if (StringUtils.isEmpty(loginName)) {
            return false;
        }
        return !userService.existLoginName(loginName);
    }

    @GetMapping("/users/add_new.htm")
    public ModelAndView addNew() {
        return new ModelAndView("/user.ftl");
    }

    public static void main(String[] args) {
        System.out.println(YvanUtil.createUUID());
        System.out.println(YvanUtil.createUUID());
        System.out.println(YvanUtil.createUUID());
        System.out.println(YvanUtil.createUUID());

    }
}
